package com.zmn.oms.zmn.business.impl.work;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.common.data.common.dro.brand.BrandDRO;
import com.zmn.base.common.data.dubbo.interfaces.brand.BrandListRemoteService;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import com.zmn.base.product.common.dto.product.ProductBaseQuery;
import com.zmn.base.product.common.dto.product.ec.ProductBaseDRO;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductForeignListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.DictModel;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.gms.dubbo.interfaces.grid.online.order.GridOrderListRemoteService;
import com.zmn.manager.lts.interfaces.task.TaskManager;
import com.zmn.manager.redis.RedisManager;
import com.zmn.manager.redis.lock.DistributedLock;
import com.zmn.manager.redis.lock.DistributedLockUtils;
import com.zmn.oms.business.interfaces.conf.channel.ConfOrderChannelBService;
import com.zmn.oms.business.interfaces.conf.workturn.bizmode.PlatBizModeBService;
import com.zmn.oms.business.interfaces.conf.workturn.servcategory.PlatServCategoryBService;
import com.zmn.oms.business.interfaces.messageV1.common.MessageGetSendInfoService;
import com.zmn.oms.business.interfaces.operation.OrderOperationBService;
import com.zmn.oms.business.interfaces.product.OrderProductExtendBService;
import com.zmn.oms.business.interfaces.serviceitem.OrderServiceItemBService;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.business.interfaces.work.OrderWorkBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.dro.conf.channel.ConfOrderChannelDRO;
import com.zmn.oms.common.dto.MapDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.MobileUtil;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.dto.acceptance.OrderWorkAcceptanceDTO;
import com.zmn.oms.model.dto.serviceitem.AddOrderServiceItemDTO;
import com.zmn.oms.model.dto.serviceitem.ServiceItemDetailDTO;
import com.zmn.oms.model.dto.serviceitem.TieredTotalPriceDTO;
import com.zmn.oms.model.dto.work.masterwork.ModifyDutyTimeDTO;
import com.zmn.oms.model.dto.work.masterwork.ModifyProductDTO;
import com.zmn.oms.model.dto.work.masterwork.ModifyQuotationDTO;
import com.zmn.oms.model.dto.work.modify.AppliqueUpdateDTO;
import com.zmn.oms.model.dto.work.modify.CheckQuotationTypeOrderDTO;
import com.zmn.oms.model.dto.work.modify.OrderTurnDTO;
import com.zmn.oms.model.dto.work.modify.amount.ZsDiscountDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.masterworking.MasterWorking;
import com.zmn.oms.model.entity.member.OrderMember;
import com.zmn.oms.model.entity.operation.OrderOperation;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.product.OrderProductExtend;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItemCell;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.work.ZsNormalUpdateOrderProductVO;
import com.zmn.oms.model.vo.work.ZsNormalUpdateOrderVO;
import com.zmn.oms.services.interfaces.conf.workturn.bizmode.PlatBizModeService;
import com.zmn.oms.services.interfaces.conf.workturn.biztype.PlatBizTypeService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.factory.OrderFactoryService;
import com.zmn.oms.services.interfaces.masterworking.MasterWorkingService;
import com.zmn.oms.services.interfaces.member.OrderMemberService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.services.interfaces.work.financework.FinanceWorkService;
import com.zmn.oms.zmn.business.interfaces.acceptance.OrderWorkAcceptanceBService;
import com.zmn.oms.zmn.business.interfaces.quotation3.OrderQuotation3ModifyBService;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkAssignBService;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkModifyProductBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkScheduleBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import com.zmn.oms.zmn.normal.business.interfaces.discount.ZsNormalOrderDiscountBService;
import com.zmn.oms.zmn.normal.business.interfaces.serviceitem.ZsNormalOrderServiceItemBService;
import com.zmn.saas.dubbo.interfaces.quotation.QuotationModifyRemoteService;
import com.zmn.sp.dubbo.interfaces.available.AvailableAreaListRemoteService;
import com.zmn.sp.dubbo.interfaces.rule.ServiceRuleListRemoteService;
import com.zmn.vas.common.dro.CheckDRO;
import com.zmn.vas.dubbo.interfaces.order.VasOrderListRemoteService;
import com.zmn.xno.dubbo.interfaces.call.CallRecordQueryRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.zmn.oms.common.constant.ChannelConsts.CHANNEL_ID_ASSIGN_VIRTUAL_COMANY_LIST;

/**
 * 类描述：工单 service
 *
 * @author lujia
 * @date 2018/12/03 17:03
 */
@Service
@Slf4j
public class ZsOrderWorkBServiceImpl implements ZsOrderWorkBService {

    @Autowired
    OrderWorkListBService orderWorkListBService;
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderWorkBService orderWorkBService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    FinanceWorkService financeWorkService;
    @Autowired
    OrderFactoryService orderFactoryService;
    @Autowired
    private ZsOrderWorkBService zsOrderWorkBService;
    @Autowired
    private OrderWorkModifyProductBService orderWorkModifyProductBService;
    @Autowired
    OrderProductExtendBService orderProductExtendBService;
    @Autowired
    OrderProductService orderProductService;
    @Autowired
    OrderServiceItemBService orderServiceItemBService;
    @Autowired
    OrderServiceItemService orderServiceItemService;
    @Autowired
    OrderOperationBService orderOperationBService;
    @Autowired
    private OrderWorkAssignBService orderWorkAssignBService;
    @Autowired
    MasterWorkingService masterWorkingService;
    @Autowired
    TaskManager taskManager;
    @Autowired
    OrderMemberService orderMemberService;
    @Autowired
    ZsNormalOrderDiscountBService zsNormalOrderDiscountBService;
    @Autowired
    MessageGetSendInfoService messageGetSendInfoService;
    @Resource
    private RedisManager redisManager;
    @Autowired
    ZsOrderWorkScheduleBService zsOrderWorkScheduleBService;
    @Autowired
    private ZsDistributeWorkBService zsDistributeWorkBService;
    @Autowired
    ZsNormalOrderServiceItemBService zsNormalOrderServiceItemBService;
    @Autowired
    ServItemBService servItemBService;
    @Autowired
    private OrderQuotation3ModifyBService orderQuotation3ModifyBService;
    @Autowired
    private OrderWorkAcceptanceBService orderWorkAcceptanceBService;
    @Resource
    private ConfOrderChannelBService confOrderChannelBService;
    @Resource
    private PlatBizModeService platBizModeService;

    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private BrandListRemoteService brandListRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private ProductForeignListRemoteService productForeignListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    AvailableAreaListRemoteService availableAreaListRemoteService;
    @Reference(version = com.zmn.sp.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
    ServiceRuleListRemoteService serviceRuleListRemoteService;
    @Reference(version = com.zmn.xno.common.constant.SystemConstants.DUBBO_CONSTS_INTERFACE_VERSION, check = false)
    CallRecordQueryRemoteService callRecordQueryRemoteService;
    @Reference(version = com.zmn.vas.dubbo.consts.VasDubboConsts.INTERFACE_VERSION, check = false)
    VasOrderListRemoteService vasOrderListRemoteService;
    @Reference(version = com.zmn.saas.dubbo.constant.SaasDubboConsts.INTERFACE_VERSION, check = false)
    QuotationModifyRemoteService quotationModifyRemoteService;
    @Reference(version = com.zmn.gms.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    GridOrderListRemoteService gridOrderListRemoteService;

    @Resource
    private PlatBizTypeService platBizTypeService;
    @Resource
    private PlatBizModeBService platBizModeBService;
    @Resource
    private PlatServCategoryBService platServCategoryBService;

    @Override
    public void updateApplique(AppliqueUpdateDTO appliqueUpdateDTO) {
        OrderWork orderWork = new OrderWork();
        orderWork.setOrderId(appliqueUpdateDTO.getOrderId());
        orderWork.setWorkId(appliqueUpdateDTO.getWorkId());
        orderWork.setAppliqueStatus(appliqueUpdateDTO.getStatus());
        orderWork.setCurrentRemark(appliqueUpdateDTO.getOperatorRemark());
        financeWorkService.updateAppliqueStatus(orderWork);
    }

    @Override
    public ZsNormalUpdateOrderVO findUpdateOrderWorkVO(Long orderId, Long workId) {
        OrderBO orderBO = orderWorkBService.findOrderWork(orderId, workId);
        return this.findUpdateOrderWorkVO(orderBO);
    }

    @Override
    public ZsNormalUpdateOrderVO findUpdateOrderWorkVO(OrderBO orderBO) {
        Objects.requireNonNull(orderBO);

        ZsNormalUpdateOrderVO zsNormalUpdateOrderVO = BeanMapper.map(orderBO.getOrder(), ZsNormalUpdateOrderVO.class);
        if (Objects.isNull(zsNormalUpdateOrderVO)) {
            zsNormalUpdateOrderVO = new ZsNormalUpdateOrderVO();
        }
        BeanMapper.copy(orderBO.getOrderWork(), zsNormalUpdateOrderVO);
        BeanMapper.copy(orderBO.getOrderDetail(), zsNormalUpdateOrderVO);

        zsNormalUpdateOrderVO.setHideTelephone(MobileUtil.formatHideTel(zsNormalUpdateOrderVO.getTelephone()));
        zsNormalUpdateOrderVO.setHideTelephone2(MobileUtil.formatHideTel(zsNormalUpdateOrderVO.getTelephone2()));
        zsNormalUpdateOrderVO.setHideTelephone3(MobileUtil.formatHideTel(zsNormalUpdateOrderVO.getTelephone3()));

        zsNormalUpdateOrderVO.setOrderProductList(BeanMapper.mapList(orderBO.getOrderProductList(), ZsNormalUpdateOrderProductVO.class));
        zsNormalUpdateOrderVO.setProductShowType(!NumberUtil.isNullOrZero(orderBO.getOrderWork().getProductId()) ? GlobalConsts.NO : GlobalConsts.YES); // 设置产品类型

        // 故障数据处理
        zsNormalUpdateOrderVO.getOrderProductList().forEach(item -> {
            if (StringUtils.isNotBlank(item.getFault())) {
                try {
                    List<MapDTO> faultList = JSON.parseArray(item.getFault(), MapDTO.class);
                    item.setFaultIdList(Optional.ofNullable(faultList).orElse(Lists.newArrayListWithCapacity(0)).stream().map(MapDTO::getMapId).collect(Collectors.toList()));
                } catch (Exception ex) {
                }
            }
        });
        if (NumberUtil.isNullOrZero(zsNormalUpdateOrderVO.getReworkId())) {
            zsNormalUpdateOrderVO.setReworkId(null);
        }

        // 厂商单
        if (Objects.equals(OrderConsts.ORDER_SOURCE_TYPE_FACTORY, orderBO.getOrderWork().getSourceType())) {
            zsNormalUpdateOrderVO.setOrderFactory(orderFactoryService.findOrderFactoryByKey(orderBO.getOrderWork().getOrderId()));
        }

        // 是否已领单
        //zsNormalUpdateOrderVO.setTake(orderBO.getOrderWork().getStatus() >= OrderStatusConsts.WORK_STATUS_TAKE);

        return zsNormalUpdateOrderVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_TURN, beforeProceed = false)
    public void saveTurn(OrderTurnDTO orderTurnDTO) throws OmsBaseException {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderTurnDTO.getOrderId(), orderTurnDTO.getWorkId());
        Integer servItemType = null;
        Integer sourceType = null;

        if (Objects.equals(orderTurnDTO.getPlatWork(), GlobalConsts.PLAT_MARK_ZMN)) {
            // 重新设置计价器类型
            CheckQuotationTypeOrderDTO checkQuotationTypeOrderDTO = BeanMapper.map(orderWork, CheckQuotationTypeOrderDTO.class);
            checkQuotationTypeOrderDTO.setPlatWork(orderTurnDTO.getPlatWork());
            checkQuotationTypeOrderDTO.setCompatibilityFinalPrice(true);
            servItemType = servItemBService.getServItemType(checkQuotationTypeOrderDTO); // 设置工单计价类型

            // 重新设置来源类型
            ResponseDTO<CheckDRO> checkDROResponseDTO = vasOrderListRemoteService.checkIsTakeOrderByUserId(orderWork.getUserId());
            if (!Objects.isNull(checkDROResponseDTO.getData())) {
                CheckDRO checkDRO = checkDROResponseDTO.getData();
                if (Objects.equals(GlobalConsts.YES, checkDRO.getResult())) {
                    sourceType = OrderConsts.ORDER_SOURCE_TYPE_MEMBER;
                }
            }
        }
        // 转单到非啄木鸟平台
        else {
            // 设置为非计价类型
            if (servItemBService.isQuotationType(orderWork.getServItemType())) {
                servItemType = OrderConsts.SERVICE_ITEM_TYPE_ORDER;
                orderServiceItemService.deleteByOrderId(orderWork.getOrderId());// 删除服务项

                // 计价器3.0订单 清除报价流程数据
                if (Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)) {
                    orderQuotation3ModifyBService.clearQuotationInfo(orderWork.getOrderId(), orderWork.getWorkId(), true);
                }
            }
            // 原先是特权单，改回普通单类型
            if (Objects.equals(orderWork.getSourceType(), OrderConsts.ORDER_SOURCE_TYPE_MEMBER)) {
                sourceType = OrderConsts.ORDER_SOURCE_TYPE_NORMAL;
            }
        }

        // 将转单平台放入orderWork，再进行平台直派判断
        orderWork.setPlatWork(orderTurnDTO.getPlatWork());
        boolean isGrid = zsDistributeWorkBService.isGridDistributeByConfig(orderWork);

        log.debug("[{}]转单源平台[{}]目标平台[{}]设置普通计价类型[{}]，设置来源类型[{}]", orderTurnDTO.getOrderId(), orderWork.getPlatWork(), orderTurnDTO.getPlatWork(), servItemType, sourceType);
        // 2，转单
        OrderWork updateOrderWork = BeanMapper.map(orderTurnDTO, OrderWork.class);
        updateOrderWork.setServItemType(servItemType);// 转单设置计价类型
        updateOrderWork.setTurnerId(orderTurnDTO.getOperatorId());
        updateOrderWork.setTurnTime(DateUtil.getNow());
        updateOrderWork.setSourceType(sourceType);
        if (isGrid) {
            updateOrderWork.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_PLAT);
        } else {
            updateOrderWork.setDistributeWay(OrderDistributeConsts.DISTRIBUTE_WAY_SP);
        }

        // 转单后，修改服务合同模式 - 统一调用dubble接口
        Integer plat = platBizModeService.findByPlat(orderTurnDTO.getPlatWork());
        updateOrderWork.setBizMode(plat);
        orderWorkService.updatePlatWorkById(updateOrderWork);
    }

    @Override
    public Boolean saveAutoTurn(Long orderId) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderId, orderId);
        if (orderWork == null) {
            log.info("#order#autoTurn {} 订单不存在", orderId);
            return false;
        }

        ConfOrderChannelDRO confOrderChannelDRO = null;
        try {
            confOrderChannelDRO = confOrderChannelBService.getByChannelId(orderWork.getChannelId());
        } catch (OmsBaseException omsBaseException) {
            omsBaseException.printStackTrace();
        }
        if (Objects.nonNull(confOrderChannelDRO) && Objects.equals(confOrderChannelDRO.getOrderTransferType(), com.zmn.consts.GlobalConsts.NO)) {
            log.info("#order#autoTurn {} 指定渠道不允许转单", orderId);
            return false;
        }

        if (OrderStatusConsts.WORK_STATUS_ASSIGN <= orderWork.getStatus() || !Objects.equals(OrderStatusConsts.WORK_RESULT_DOING, orderWork.getResultStatus())) {
            log.info("#order#autoTurn {} 非已确认状态，无需自动转单", orderId);
            return false;
        }

        OrderDetail orderDetail = orderDetailService.findOrderDetailByKeySrcMaster(orderId);
        if (!Objects.equals(GlobalConsts.NO, orderDetail.getInScopeService())) {
            log.info("#order#autoTurn {}在服务范围，无需自动转单", orderId);
            return false;
        }

//        if (orderDetail.getLatitude() == null || orderDetail.getLongitude() == null) {
//            log.info("#order#autoTurn {} 经纬度为空，无需自动转单", orderId);
//            return false;
//        }

        if (Objects.equals(orderWork.getMember(), GlobalConsts.YES) || Objects.equals(orderWork.getSourceType(), OrderConsts.ORDER_SOURCE_TYPE_BCUSTOMER)) {
            log.info("#order#autoTurn {} 会员单/政企单，不可转单", orderId);
            return false;
        }

        Integer targetPlat = this.getManagePlat(orderWork, orderDetail);
        if (Objects.isNull(targetPlat)) {
            log.info("#order#autoTurn {} targetPlat 为空，不可转单", orderId);
            return false;
        }

        if (Objects.equals(orderWork.getPlatWork(), targetPlat)) {
            log.info("#order#autoTurn {} 转单平台和已有平台一致，不需要转单，防止死循环", orderId);
            return false;
        }

        // 返修单不能自动转单
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REWORK)) {
            log.info("#order#autoTurn {} 返修单不能自动转单", orderId);
            return false;
        }

        OrderTurnDTO orderTurnDTO = new OrderTurnDTO();
        orderTurnDTO.setOrderId(orderId);
        orderTurnDTO.setWorkId(orderId);
        orderTurnDTO.setPlatWork(targetPlat);
        orderTurnDTO.setOperator(GlobalConsts.getOperatorTypeName(GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
        orderTurnDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        orderTurnDTO.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        orderTurnDTO.setOperatorRemark("自动转单");
        try {
            zsOrderWorkBService.saveTurn(orderTurnDTO);
            log.info("#order#autoTurn {} 自动转单至 {}", orderId, GlobalConsts.getPlatName(targetPlat));
        } catch (Exception e) {
            log.error("#order#autoTurn {} 自动转单异常 {} {}", orderId, e.getMessage(), e);
            return false;
        }
        return true;
    }

    /**
     * 转单后自动确认的校验
     */
    @Override
    public Boolean checkTurnStatus(Long orderId, Long workId) {
        // 新增逻辑：转单后自动确认的校验，即：产品ID为正常状态、有经纬度、有预约时间（限：服务平台是啄木鸟和川南环保）；若不满足，则订单状态变更至：已录入-进行中
        OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderId, workId);
        ProductBaseQuery productDIO = new ProductBaseQuery();
        productDIO.setProductId(orderWork.getProductId());
        List<ProductBaseDRO> productDROS = productForeignListRemoteService.listBaseDROByQuery(productDIO).getData();
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKeySrcMaster(orderId);
        boolean result = false;

        // 言而有信厂商单，允许经纬度为空
        if (Objects.equals(GlobalConsts.PLAT_MARK_YEYX, orderWork.getPlatWork()) &&
                Objects.equals(OrderConsts.ORDER_SOURCE_TYPE_FACTORY, orderWork.getSourceType()) &&
                CollectionUtil.isNotNullOrEmpty(productDROS) && orderDetail.getLatitude() == null) {
            return true;
        }

        if (CollectionUtil.isNotNullOrEmpty(productDROS) && orderDetail.getLatitude() != null && orderDetail.getLongitude() != null) {
            if (Objects.equals(com.zmn.consts.GlobalConsts.BIZ_TYPE_F, orderWork.getSourceType()) || Objects.nonNull(orderWork.getDutyTime())) {
                result = true;
            }
        }
        return result;
    }

    /**
     * 订单状态变更
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_CHANGE_STATUS, beforeProceed = false)
    public void changeTurnStatus(OrderTurnDTO orderTurnDTO) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderTurnDTO.getOrderId(), orderTurnDTO.getWorkId());
        orderWork.setStatus(OrderStatusConsts.WORK_STATUS_INPUT);
        orderWork.setResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
        try {
            orderWorkService.updateOrderWorkByKey(orderWork);
        } catch (Exception e) {
            log.error("转单后自动确认的校验后修改订单状态失败：{}" + e.getMessage());
        }
    }

    private Integer getManagePlat(OrderWork orderWork, OrderDetail orderDetail) {

        // 指定渠道，自动转回下单平台
        if (CHANNEL_ID_ASSIGN_VIRTUAL_COMANY_LIST.contains(orderWork.getChannelId())) {
            log.info("#order#autoTurn {} 指定渠道，自动转回下单平台", orderWork.getOrderId());
            return orderWork.getPlat();
        }

        // 返修单或退款单 服务平台自动为源单平台
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REWORK)) {
            OrderWork sourceOrderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderWork.getReworkId(), orderWork.getReworkId());
            return sourceOrderWork.getPlat();
        }
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REFUND)) {
            OrderWork sourceOrderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderWork.getOriginalId(), orderWork.getOriginalId());
            return sourceOrderWork.getPlat();
        }

        // 根据服务商判断转单平台
        /*if (NumberUtil.isNotNullOrZero(orderWork.getManageCompanyId())) {
            SpAvailableAreaCheckDIO spAvailableAreaCheckDIO = new SpAvailableAreaCheckDIO();
            spAvailableAreaCheckDIO.setManageCompanyId(orderWork.getManageCompanyId());
            spAvailableAreaCheckDIO.setBizType(orderWork.getBizType());
            spAvailableAreaCheckDIO.setShowProductId(orderWork.getShowProductId());
            spAvailableAreaCheckDIO.setLongitude(orderDetail.getLongitude());
            spAvailableAreaCheckDIO.setLatitude(orderDetail.getLatitude());
            spAvailableAreaCheckDIO.setCountyId(orderDetail.getCountyId());

            // F单支持无经纬度可分单，如果不是F单，没有经纬度直接返回，不需要再调接口
            if (Objects.equals(orderWork.getBizType(), com.zmn.consts.GlobalConsts.BIZ_TYPE_F) ||
                    Objects.nonNull(orderDetail.getLatitude()) || Objects.nonNull(orderDetail.getLongitude())){
                log.debug("#order#autoTurn 判断此位置是否在此服务的服务范围内 入参 spAvailableAreaCheckDIO:{}", JSON.toJSONString(spAvailableAreaCheckDIO));
                ResponseDTO<Boolean> response = availableAreaListRemoteService.checkSpAvailableArea(spAvailableAreaCheckDIO);
                log.debug("#order#autoTurn 判断此位置是否在此服务的服务范围内 出参：{}", response);
                if (response.getData()) {
                    log.debug("#order#autoTurn 获取公司信息 入参：{}", orderWork.getManageCompanyId());
                    ResponseDTO<CompanyDRO> companyResponse = baseCompanyListRemoteService.getCompanyByCompanyId(orderWork.getManageCompanyId());
                    log.debug("#order#autoTurn 获取公司信息 出参：{}", JSONObject.toJSONString(companyResponse));
                    return companyResponse.getData().getPlat();
                }
            }
        }*/

        // 通用：判断开通区域 + 开通服务
        List<DictModel> managePlatList = this.getManagePlatList(orderWork, orderDetail);
        if (managePlatList.size() == 1) {
            return managePlatList.get(0).getKey();
        } else if(managePlatList.size() > 1){
            // 如果服务平台为多个 根据前台产品优先级选择
            Integer plat = managePlatList.get(0).getKey();
            List<Integer> collect = managePlatList.stream().map(DictModel::getKey).collect(Collectors.toList());
            ProductBaseQuery productDIO = new ProductBaseQuery();
            productDIO.setProductId(orderWork.getShowProductId());
            ResponseDTO<List<ProductBaseDRO>> productResponseDTO = productForeignListRemoteService.listBaseDROByQuery(productDIO);
            if(productResponseDTO.isSuccess() && CollectionUtil.isNotNullOrEmpty(productResponseDTO.getData())){
                ProductBaseDRO productBaseDRO = productResponseDTO.getData().get(0);
                if(collect.contains(productBaseDRO.getPriorityFirst())){
                    plat = productBaseDRO.getPriorityFirst();
                }else if (collect.contains(productBaseDRO.getPrioritySecond())){
                    plat = productBaseDRO.getPrioritySecond();
                }else {
                    plat = productBaseDRO.getPriorityThird();
                }
            }
            log.info("#order#autoTurn {} 可服务平台不唯一 根据前台产品优先级选择 plat：{}", orderWork.getOrderId(), plat);
            return plat;
        }
        // 原平台不能分单时才需要转单
        return null;
    }

    /**
     * 获取客服务平台列表
     *
     * @param orderWork
     * @param orderDetail
     * @return
     */
    @Override
    public List<DictModel> getManagePlatList(OrderWork orderWork, OrderDetail orderDetail) {
        List<DictModel> managePlats = Lists.newArrayList();
        List<DictModel> plats = GlobalConsts.getPlatList();
        plats.forEach(dictModel -> {

            // 转单业务类型判断
            List<Integer> bizTypeList = platBizTypeService.listBizTypeByPlat(dictModel.getKey());
            if (CollectionUtils.isEmpty(bizTypeList)) {
                return;
            }
            if(!bizTypeList.contains(orderWork.getBizType())){
                return;
            }

            // 检查平台是否开通服务分类
            boolean checkCategory = zsOrderWorkBService.checkOpenCategByPlatAndCateg(dictModel.getKey(), orderWork.getServCategId(), orderWork.getShowCategId());
            if (!checkCategory) {
                return;
            }

            managePlats.add(dictModel);

            /*ProductAndAddressDIO productAndAddressDIO = new ProductAndAddressDIO();
            productAndAddressDIO.setPlat(dictModel.getKey());
            productAndAddressDIO.setBizType(orderWork.getBizType());
            productAndAddressDIO.setShowProductId(orderWork.getShowProductId());
            productAndAddressDIO.setCountyId(orderDetail.getCountyId());
            if (Objects.equals(orderDetail.getStreetSource(), OrderConsts.STREET_SOURCE_NONE) ||
                    Objects.equals(orderDetail.getStreetSource(), OrderConsts.STREET_SOURCE_DEFAULT)) {
                productAndAddressDIO.setStreetId(orderDetail.getStreetId());
            } else {
                productAndAddressDIO.setStreetId(0);
            }
            productAndAddressDIO.setLongitude(orderDetail.getLongitude());
            productAndAddressDIO.setLatitude(orderDetail.getLatitude());
            // F单支持无经纬度可分单，如果不是F单，没有经纬度直接返回，不需要再调接口
            if (!Objects.equals(orderWork.getBizType(), com.zmn.consts.GlobalConsts.BIZ_TYPE_F) &&
                    Objects.isNull(orderDetail.getLatitude()) && Objects.isNull(orderDetail.getLongitude())){
                log.debug("#order#autoTurn 该订单不是F单并且没有经纬度直接返回");
                return;
            }
            log.debug("#order#autoTurn listSpByProductAndAddress 判断平台是否可以服务此工单 productAndAddressDIO:{}", JSON.toJSONString(productAndAddressDIO));
            ResponseDTO<List<SpServProviderDRO>> listResponseDTO = serviceRuleListRemoteService.listSpByProductAndAddress(productAndAddressDIO);
            log.debug("#order#autoTurn listSpByProductAndAddress 判断平台是否可以服务此工单 出参,{}", JSON.toJSONString(listResponseDTO));

            List<SpServProviderDRO> manageCompanyDROList = listResponseDTO.getData();
            // 口碑渠道--不分单给家修匠
            if (Objects.equals(ChannelConsts.CHANNEL_ID_KOUBEI, orderWork.getChannelId())) {
                manageCompanyDROList = manageCompanyDROList.stream()
                        .filter(e -> !Objects.equals(e.getSubCompanyId(), CompanyConsts.ZMN_JXJ_COMPANY_ID))
                        .collect(Collectors.toList());
            }

            if (CollectionUtil.isNotNullOrEmpty(manageCompanyDROList)) {
                List<Integer> manageCompanyIds = manageCompanyDROList.stream().map(SpServProviderDRO::getSpId).collect(Collectors.toList());
                // 收款限制过滤
                List<Integer> listCanServCompanyFilterLimit = orderWorkAssignBService.listCanServCompanyFilterPaymentLimit(manageCompanyIds, orderWork.getChannelId(), orderWork.getBizType());
                // 库存限制过滤（有预约时间 & 新单才过滤库存）
                if (orderWork.getDutyTime() != null && Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)) {
                    OrderStockDTO build = OrderStockDTO.builder()
                            .plat(orderWork.getPlatWork())
                            .cityId(orderWork.getCityId())
                            .servCategId(orderWork.getServCategId())
                            .showCategId(orderWork.getShowCategId())
                            .date(orderWork.getDutyTime())
                            .build();
                    listCanServCompanyFilterLimit = orderWorkAssignBService.listCanServCompanyFilterStockLimit(listCanServCompanyFilterLimit, build);
                }
                List<Integer> finalListCanServCompanyFilterPaymentLimit = listCanServCompanyFilterLimit;
                manageCompanyDROList = manageCompanyDROList.stream()
                        .filter(e-> finalListCanServCompanyFilterPaymentLimit.contains(e.getSpId()))
                        .collect(Collectors.toList());
                if (manageCompanyDROList.size() > 0) {
                    managePlats.add(dictModel);
                }
            }*/

        });
        return managePlats;
    }

    /**
     * 修改报价
     * @param modifyQuotationDTO
     * @throws OmsBaseException
     */
    @Override
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_QUOTATION, beforeProceed = false)
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderQuotation(ModifyQuotationDTO modifyQuotationDTO) throws OmsBaseException {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(modifyQuotationDTO.getOrderId(),
                modifyQuotationDTO.getWorkId());

        // 已取消
        if (Objects.equals(OrderStatusConsts.WORK_RESULT_DISCARD, orderWork.getResultStatus())) {
            throw new OmsBaseException("此订单已取消，无法操作");
        }

        // 进行中，状态是完成以前的订单，才允许修改报价
        if (!Objects.equals(OrderStatusConsts.WORK_RESULT_DOING, orderWork.getResultStatus())
                || orderWork.getStatus() >= OrderStatusConsts.ORDER_STATUS_COMPLETE) {
            throw new OmsBaseException("此订单当前状态已不允许修改报价");
        }

        // 如果是非计价器订单
        if (!servItemBService.isQuotationType(orderWork.getServItemType())) {
            throw new OmsBaseException("此订单为非计价器订单");
        }

        if (modifyQuotationDTO.getMasterId() == null) {
            modifyQuotationDTO.setMasterId(orderWork.getMasterId());
        }

        OrderMember orderMember = orderMemberService.findMemberByKey(orderWork.getOrderId());
        if (!Objects.isNull(orderMember) && NumberUtil.isNotNullOrZero(orderWork.getOriginalAmount())) {
            boolean reviewSuccess = orderMember.getReviewStatus() == OrderConsts.ORDER_MEMBER_REVIEW_STATUS_PLAT_SUCCESS;
            if (reviewSuccess) {
                throw new OmsBaseException("工单为审核通过的延保订单，无法操作");
            }
        }

        String lockKey = String.format(LockConsts.LOCK_ORDER_UPDATE_QUOTATION, orderWork.getOrderId(), orderWork.getWorkId());
        DistributedLock lock = DistributedLockUtils.build(lockKey, LockConsts.LOCK_VALID_TIME);
        try {
            if (lock.tryLock()) {
                this.doUpdateOrderQuotation(orderWork, modifyQuotationDTO);
            }
        } catch (OmsBaseException oe) {
            throw oe;
        } catch (Exception e) {
            throw new OmsBaseException("修改报价失败");
        } finally {
            lock.unlock();
        }
    }

    /**
     * 修改报价相关的数据
     * @param orderWork
     * @param modifyQuotationDTO
     * @throws OmsBaseException
     */
    protected void doUpdateOrderQuotation(OrderWork orderWork, ModifyQuotationDTO modifyQuotationDTO) throws OmsBaseException {

        boolean hasServiceItems = !CollectionUtils.isEmpty(modifyQuotationDTO.getOrderServiceItems());
        boolean productChanged = (!Objects.equals(orderWork.getProductId(), modifyQuotationDTO.getProductId()));

        // 修改产品
        if (productChanged) {
            ModifyProductDTO modifyProductDTO = BeanMapper.map(modifyQuotationDTO, ModifyProductDTO.class);
            orderWorkModifyProductBService.updateOrderProduct(modifyProductDTO);
        }

        // 修改品牌信息
        if (modifyQuotationDTO.getBrandId() != null) {
            List<OrderProduct> productList = orderProductService.listOrderProductByOrderIdSrcMaster(modifyQuotationDTO.getOrderId());
            OrderProduct orderProduct = null;
            for (OrderProduct item : productList) {
                if (Objects.equals(item.getProductId(), modifyQuotationDTO.getProductId())) {
                    orderProduct = item;
                }
            }

            if (orderProduct != null && !Objects.equals(modifyQuotationDTO.getBrandId(), orderProduct.getBrandId())) {
                if (NumberUtil.isNullOrZero(modifyQuotationDTO.getBrandId())) {
                    OrderProduct updateOrderProduct = new OrderProduct();
                    updateOrderProduct.setProId(orderProduct.getProId());
                    updateOrderProduct.setBrandId(0);
                    updateOrderProduct.setBrandName("其它");
                    orderProductService.updateBrandByKey(updateOrderProduct);

                    // 记录品牌变化日志
                    String oldRemark = Optional.ofNullable(modifyQuotationDTO.getOperatorLogRemark()).orElse("");
                    modifyQuotationDTO.setOperatorLogRemark(String.format("%s；品牌变更：%s-->%s", oldRemark,
                            orderProduct.getBrandName(), updateOrderProduct.getBrandName()));
                } else {
                    ResponseDTO<BrandDRO> baseBrandResponseDTO = brandListRemoteService.getById(modifyQuotationDTO.getBrandId());
                    BrandDRO baseBrandDRO = baseBrandResponseDTO.getData();
                    if (baseBrandDRO != null) {
                        OrderProduct updateOrderProduct = new OrderProduct();
                        updateOrderProduct.setProId(orderProduct.getProId());
                        updateOrderProduct.setBrandId(baseBrandDRO.getBrandId());
                        updateOrderProduct.setBrandName(baseBrandDRO.getName());
                        orderProductService.updateBrandByKey(updateOrderProduct);

                        // 记录品牌变化日志
                        String oldRemark = Optional.ofNullable(modifyQuotationDTO.getOperatorLogRemark()).orElse("");
                        modifyQuotationDTO.setOperatorLogRemark(String.format("%s；品牌变更：%s-->%s", oldRemark,
                                orderProduct.getBrandName(), updateOrderProduct.getBrandName()));
                    }
                    else {
                        log.info("没查到对应品牌：brandId=[{}]", modifyQuotationDTO.getBrandId());
                    }
                }

            }
        }

        // 保存服务项
        if (hasServiceItems) {
            List<OrderProductExtend> orderProductExtendList = orderProductExtendBService.getOrderProductExtend(modifyQuotationDTO.getOrderId());

            AddOrderServiceItemDTO addOrderServiceItemDTO = BeanMapper.map(modifyQuotationDTO, AddOrderServiceItemDTO.class);
            addOrderServiceItemDTO.setOrderServiceItemList(modifyQuotationDTO.getOrderServiceItems());
            addOrderServiceItemDTO.setProExtId(orderProductExtendList.get(0).getProExtId());
            addOrderServiceItemDTO.setIsProductChanged(productChanged);
            // 是否存在阶梯价格
            Integer tieredTotalPrice = addOrderServiceItemDTO.getOrderServiceItemList().stream().filter(e -> e.getTieredTotalPrice() != null).mapToInt(OrderServiceItem::getTieredTotalPrice).sum();
            if (NumberUtil.isNotNullOrZero(tieredTotalPrice)) {
                addOrderServiceItemDTO.getOrderServiceItemList().forEach(orderServiceItem -> {
                    // 如果不存在阶梯价跳过本次循环
                    if (NumberUtil.isNullOrZero(orderServiceItem.getTieredTotalPrice())) {
                        return;
                    }
                    // 如果数量小于1跳过本次循环
                    if (orderServiceItem.getNumber() < 1) {
                        return;
                    }

                    // 处理内部价阶梯价，如果内部价为空，则直接使用销售价阶梯总价。否则计算内部价阶梯总价
                    if (Objects.isNull(orderServiceItem.getInternalSettlementPrice())) {
                        orderServiceItem.setInternalSettlementPrice(orderServiceItem.getItemPrice());
                        orderServiceItem.setInternalTotalPrice(orderServiceItem.getTieredTotalPrice());
                    } else {
                        TieredTotalPriceDTO tieredTotalPriceDTO = new TieredTotalPriceDTO();
                        tieredTotalPriceDTO.setOrderId(addOrderServiceItemDTO.getOrderId());
                        tieredTotalPriceDTO.setItemId(orderServiceItem.getServItemId());
                        tieredTotalPriceDTO.setNumber(orderServiceItem.getNumber());
                        tieredTotalPriceDTO.setPrice(orderServiceItem.getInternalSettlementPrice());

                        List<OrderServiceItemCell> itemCellList = orderServiceItem.getItemDetailList();
                        if (CollectionUtil.isNotNullOrEmpty(itemCellList)) {
                            List<ServiceItemDetailDTO> detailList = new ArrayList<>(itemCellList.size());
                            for (OrderServiceItemCell cell : itemCellList) {
                                ServiceItemDetailDTO detailDTO = new ServiceItemDetailDTO();
                                detailDTO.setItemCellId(cell.getItemCellId());
                                detailDTO.setItemCellName(cell.getItemCellName());
                                detailDTO.setCellPrice(cell.getCellPrice());
                                detailDTO.setSort(cell.getSort());
                                detailList.add(detailDTO);
                            }
                            tieredTotalPriceDTO.setDetailList(detailList);
                        }
                        orderServiceItem.setInternalTotalPrice(zsNormalOrderServiceItemBService.listTieredTotalPrice(tieredTotalPriceDTO));
                    }

                    // 处理外部价阶梯价，如果外部价为空，则直接使用销售价阶梯总价。否则计算外部价阶梯总价
                    if (Objects.isNull(orderServiceItem.getExternalSettlementPrice())) {
                        orderServiceItem.setExternalSettlementPrice(orderServiceItem.getItemPrice());
                        orderServiceItem.setExternalTotalPrice(orderServiceItem.getTieredTotalPrice());
                    } else {
                        TieredTotalPriceDTO tieredTotalPriceDTO = new TieredTotalPriceDTO();
                        tieredTotalPriceDTO.setOrderId(addOrderServiceItemDTO.getOrderId());
                        tieredTotalPriceDTO.setItemId(orderServiceItem.getServItemId());
                        tieredTotalPriceDTO.setNumber(orderServiceItem.getNumber());
                        tieredTotalPriceDTO.setPrice(orderServiceItem.getExternalSettlementPrice());

                        List<OrderServiceItemCell> itemCellList = orderServiceItem.getItemDetailList();
                        if (CollectionUtil.isNotNullOrEmpty(itemCellList)) {
                            List<ServiceItemDetailDTO> detailList = new ArrayList<>(itemCellList.size());
                            for (OrderServiceItemCell cell : itemCellList) {
                                ServiceItemDetailDTO detailDTO = new ServiceItemDetailDTO();
                                detailDTO.setItemCellId(cell.getItemCellId());
                                detailDTO.setItemCellName(cell.getItemCellName());
                                detailDTO.setCellPrice(cell.getCellPrice());
                                detailDTO.setSort(cell.getSort());
                                detailList.add(detailDTO);
                            }
                            tieredTotalPriceDTO.setDetailList(detailList);
                        }
                        orderServiceItem.setExternalTotalPrice(zsNormalOrderServiceItemBService.listTieredTotalPrice(tieredTotalPriceDTO));
                    }
                });
            }

            orderServiceItemBService.insertServiceItem(addOrderServiceItemDTO);

            // 检查服务项的产品扩展id是否在产品扩展表中，若不存在删除该服务项
            Set<Long> proExtIds = orderProductExtendList.stream().map(e -> e.getProExtId()).collect(Collectors.toSet());
            List<OrderServiceItem> orderServiceItems = orderServiceItemService.listByOrderIdSrcMaster(modifyQuotationDTO.getOrderId());
            List<Long> collect = orderServiceItems.stream().map(e -> e.getProExtId()).distinct().collect(Collectors.toList());
            collect.forEach(e->{
                if (!proExtIds.contains(e)) {
                    orderServiceItemService.deleteByProExtId(e);
                }
            });
            //保存报价人信息
            OrderOperation orderOperation = new OrderOperation();
            orderOperation.setOrderId(modifyQuotationDTO.getOrderId());
            orderOperation.setQuotationId(modifyQuotationDTO.getOperatorId());
            orderOperation.setQuotationType(modifyQuotationDTO.getQuotationType());
            orderOperation.setQuotationName(modifyQuotationDTO.getOperator());
            orderOperation.setCreater(modifyQuotationDTO.getOperator());

            Date currentTime = new Date();
            orderOperation.setQuotationTime(currentTime);
            orderOperation.setCreateTime(currentTime);

            orderOperationBService.insertOrUpdateByKey(orderOperation);

            // 改价格删除尾款验收，需要工程师重新发起尾款验收
            OrderWorkAcceptanceDTO dto = new OrderWorkAcceptanceDTO();
            dto.setOrderId(modifyQuotationDTO.getOrderId());
            dto.setWorkId(modifyQuotationDTO.getWorkId());
            dto.setOperator(modifyQuotationDTO.getOperator());
            dto.setOperatorId(modifyQuotationDTO.getOperatorId());
            dto.setOperatorType(modifyQuotationDTO.getOperatorType());
            orderWorkAcceptanceBService.clearPaymentAcceptance(dto, orderWork);
        }

        //region
        // 是否存在优惠，如果存在则进行设置申请优惠即-工程师人工优惠
        if (NumberUtil.isNullOrZero(modifyQuotationDTO.getDiscountAmount())) {
            return;
        }
        ZsDiscountDTO discountDTO = BeanMapper.map(modifyQuotationDTO, ZsDiscountDTO.class);
        discountDTO.setDiscountAmount(modifyQuotationDTO.getDiscountAmount());
        discountDTO.setOperateId(OrderConsts.ORDER_OP_TYPE_DISCOUNT_LEVEL_ONE);

        if (discountDTO.getDiscountAmount() == 0) {
            discountDTO.setRemoveDiscount(com.zmn.consts.GlobalConsts.YES);
        } else {
            discountDTO.setRemoveDiscount(com.zmn.consts.GlobalConsts.NO);
        }

        // 保存优惠
        zsNormalOrderDiscountBService.saveDiscount(discountDTO, TriggerAmountChangeEnum.ARTIFICIAL_MASTER_DISCOUNT);

        // 人工优惠次数:如果有城市经理优惠则进行计数累加，以工程师为维度进行存储
        if (NumberUtil.isNullOrZero(modifyQuotationDTO.getCityManageDiscountAmount())) {
            return;
        }
        zsNormalOrderDiscountBService.addMasterApplyDiscountTimes(modifyQuotationDTO.getOrderId(), modifyQuotationDTO.getMasterId(), modifyQuotationDTO.getDiscountAmount());
        //endRegion
    }

    /**
     * 重置清空报价及优惠标示信息
     *
     * @param orderWork
     */
    @Override
    public void resetQuotationInfo(OrderWork orderWork) throws OmsBaseException {
        Integer masterId = Optional.ofNullable(orderWork.getMasterId()).orElse(GlobalConsts.NONE);

        // 审核标示
        String redisKeyReviewing = String.format(RedisKeyConsts.MASTER_APPLY_DISCOUNT_REVIEWING_KEY, String.valueOf(orderWork.getOrderId()), masterId);
        boolean isExistsReviewing = redisManager.exists(redisKeyReviewing);
        if (isExistsReviewing) {
            redisManager.del(redisKeyReviewing);
        }

        // 确认报价标示
        String confirmQuotationRedisKey = String.format(RedisKeyConsts.USER_HAVE_CONFIRM_QUOTATION_KEY, String.valueOf(orderWork.getOrderId()));
        boolean isExistsConfirmQuotation = redisManager.exists(confirmQuotationRedisKey);
        if (isExistsConfirmQuotation) {
            redisManager.del(confirmQuotationRedisKey);
        }

        // 清空扫码用户报价信息
        String openId = messageGetSendInfoService.getOrderUserRelationOpenId(orderWork.getOrderId(), orderWork.getPlatWork(), orderWork.getVisitUserId());
        String redisKey = String.format(RedisKeyConsts.WECHAT_SEND_QUOTATION_TEMPLATE_KEY, String.valueOf(orderWork.getWorkId()), openId);
        if (redisManager.exists(redisKey)) {
            redisManager.del(redisKey);
        }

        try {
            log.info("订单号order={}清空报价信息==>deleteQuotationByOrderId", orderWork.getOrderId());
            ResponseDTO resp = quotationModifyRemoteService.deleteQuotationByOrderId(orderWork.getOrderId());
            log.info("订单号order={}清空报价信息==>deleteQuotationByOrderId出参{}", orderWork.getOrderId(), resp);
            if (!resp.isSuccess()) {
                log.info("订单号order={}清空报价信息==>deleteQuotationByOrderId接口失败{}", orderWork.getOrderId(), resp.getMessage());
            }
        } catch (Exception e) {
            log.error("同步saas清空报价信息失败：{}", e.getMessage(), e);
            throw new OmsBaseException("同步清空报价信息失败");
        }

        if (Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE)) {
            orderQuotation3ModifyBService.clearQuotationInfo(orderWork.getOrderId(), orderWork.getWorkId(), true);
        }
    }
    /**
     * 检查平台是否开通服务分类
     * @return
     */
    @Override
    public Boolean checkOpenCategByPlatAndCateg(Integer plat, Integer servCategId, Integer categTwoId) {
        Boolean result = platServCategoryBService.checkOpenCategByPlatAndCateg(plat, servCategId, categTwoId);
        log.info("检查平台是否开通服务分类入参：plat:{},servCategId:{},showCategId:{}, 检查结果：[{}]", plat,servCategId,categTwoId, result);
        return result;
    }

    /**
     * 修改预约时间
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_MODIFY_DUTY_TIME)
    public void updateOrderDutyTime(ModifyDutyTimeDTO modifyDutyTimeDTO) throws OmsBaseException {

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(modifyDutyTimeDTO.getOrderId(), modifyDutyTimeDTO.getWorkId());
        if (orderWork == null) {
            throw new OmsBaseException("无效的工单");
        }
        if (Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_COMPLETE) ||
                !Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            throw new OmsBaseException("工单不在进行中");
        }
        // 保存新的预约时间
        OrderWork updateOrderWork = new OrderWork();
        if (Objects.nonNull(modifyDutyTimeDTO.getDutyTime()) && Objects.isNull(modifyDutyTimeDTO.getDutyStatus())) {
            updateOrderWork.setDutyStatus(OrderDutyConsts.DUTY_STATUS_SUCCESS);
        }

        updateOrderWork.setOrderId(modifyDutyTimeDTO.getOrderId());
        updateOrderWork.setWorkId(modifyDutyTimeDTO.getWorkId());
        updateOrderWork.setDutyTime(modifyDutyTimeDTO.getDutyTime());
        updateOrderWork.setDutyFailCode(modifyDutyTimeDTO.getDutyFailCode());
        updateOrderWork.setDutyStatus(modifyDutyTimeDTO.getDutyStatus());
        updateOrderWork.setNextContactTime(modifyDutyTimeDTO.getNextContactTime());
        orderWorkService.updateOrderWorkDutyTimeByKey(updateOrderWork);
        // 保存新的预约时间到进行中工单表
        MasterWorking masterWorking = new MasterWorking();
        masterWorking.setWorkId(modifyDutyTimeDTO.getWorkId());
        masterWorking.setDutyTime(modifyDutyTimeDTO.getDutyTime());
        masterWorkingService.updateWorkingDutyTimeByKey(masterWorking);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_MODIFY_DUTY_TIME)
    public void modifyDutyTime(ModifyDutyTimeDTO modifyDutyTimeDTO) throws OmsBaseException {
        // 验证预约时间范围
        zsOrderWorkScheduleBService.validateDutyTime(modifyDutyTimeDTO.getOrderId(), modifyDutyTimeDTO.getPlat(),
                ConfOrderDutyConsts.TYPE_OPERATION_PLATFORM, modifyDutyTimeDTO.getDutyTime());

        if (Objects.nonNull(modifyDutyTimeDTO.getDutyTime())) {
            modifyDutyTimeDTO.setDutyStatus(OrderDutyConsts.DUTY_STATUS_SUCCESS);
            modifyDutyTimeDTO.setNextContactTime(null);
        }

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(modifyDutyTimeDTO.getOrderId(),
                modifyDutyTimeDTO.getWorkId());

        // 判断工单状态是否是已领单和已上门，是否进行中
        if (!(Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_TAKE)
                || Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_VISIT))
                || !Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)){
            throw new OmsBaseException("工单当前状态不允许修改预约时间");
        }

        // 保存新的预约时间
        OrderWork updateOrderWork = new OrderWork();
        updateOrderWork.setWorkId(modifyDutyTimeDTO.getWorkId());
        updateOrderWork.setOrderId(modifyDutyTimeDTO.getOrderId());
        updateOrderWork.setDutyTime(modifyDutyTimeDTO.getDutyTime());
        updateOrderWork.setDutyStatus(modifyDutyTimeDTO.getDutyStatus());
        updateOrderWork.setNextContactTime(modifyDutyTimeDTO.getNextContactTime());
        orderWorkService.updateOrderWorkDutyTimeByKey(updateOrderWork);

        // 保存新的预约时间到进行中工单表
        MasterWorking masterWorking = new MasterWorking();
        masterWorking.setWorkId(modifyDutyTimeDTO.getWorkId());
        masterWorking.setDutyTime(modifyDutyTimeDTO.getDutyTime());
        masterWorkingService.updateWorkingDutyTimeByKey(masterWorking);
    }

}
